package com.rslai.commons.http.tools;

import org.apache.http.*;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;

/**
 * 压缩处理器，碰到支持压缩的网站用这个处理
 * Created by lrs on 2018/8/6.
 */
public class DeflateInterceptor implements HttpRequestInterceptor, HttpResponseInterceptor {

    public static final DeflateInterceptor instance = new DeflateInterceptor();

    /**
     * 默认构造方法
     */
    private DeflateInterceptor() {
    }

    /**
     * 处理一个请求 request
     * @param request 返回的 response
     * @param context 正在使用上下文
     * @throws HttpException HttpException
     * @throws IOException IOException
     */
    @Override
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        request.addHeader("Accept-Encoding", "gzip,deflate");
    }

    /**
     * 处理一个响应 response
     * @param response 返回的 response
     * @param context 正在使用上下文
     * @throws HttpException HttpException
     * @throws IOException IOException
     */
    @Override
    public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
        HttpEntity entity = response.getEntity();
        // 有 entity 返回才需要解压缩，例如：304 则不需要解压缩
        if (entity != null) {
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (HeaderElement codec : codecs) {
                    if ("gzip".equalsIgnoreCase(codec.getName())) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    } else if ("deflate".equalsIgnoreCase(codec.getName())) {
                        response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
                        return;
                    } else if ("identity".equalsIgnoreCase(codec.getName())) {
                        // 不需要解压缩的 content 不处理
                        return;
                    } else {
                        throw new HttpException("Unsupported Content-Coding: " + codec.getName());
                    }
                }
            }
        }
    }

}
